package com.diyunapp.xilinapp.details;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.diyunapp.xilinapp.R;
import com.diyunapp.xilinapp.adapters.RecycleViewGridAdapter;
import com.diyunapp.xilinapp.bean.YouLikeGoodsBean;
import com.diyunapp.xilinapp.main.MainActivity;
import com.diyunapp.xilinapp.myapi.OnRecyclerViewItemClickListener;
import com.diyunapp.xilinapp.selfdefine.LoadMoreRecyclerView;
import com.diyunapp.xilinapp.selfdefine.StatusBarActivity;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * Created by NIDAYE on 2016/6/17.
 */
public class SearchResultActivity extends StatusBarActivity implements View.OnClickListener {

    @Bind(R.id.searchresult_goback_ib)
    ImageButton searchresultGobackIb;
    @Bind(R.id.searchresult_search_et)
    EditText searchresultSearchEt;
    @Bind(R.id.searchresult_buycar_ib)
    ImageButton searchresultBuycarIb;
    @Bind(R.id.search_order_default_tv)
    TextView searchOrderDefaultTv;
    @Bind(R.id.search_order_sales_tv)
    TextView searchOrderSalesTv;
    @Bind(R.id.search_order_newest_tv)
    TextView searchOrderNewestTv;
    @Bind(R.id.search_order_price_tv)
    TextView searchOrderPriceTv;
    @Bind(R.id.searchgoods_recycle_view)
    LoadMoreRecyclerView searchgoodsRecycleView;
    @Bind(R.id.searchgoods_recycle_swiperefreshlayout)
    SwipeRefreshLayout searchgoodsRecycleSwiperefreshlayout;
    @Bind(R.id.search_order_price_ll)
    LinearLayout searchOrderPriceLl;
    @Bind(R.id.searchresult_search_ib)
    ImageButton searchresultSearchIb;
    @Bind(R.id.search_order_price_iv)
    ImageView searchOrderPriceIv;
    @Bind(R.id.special_search_tv)
    TextView specialSearchTv;
    @Bind(R.id.myorders_noorders_tv)
    TextView myordersNoordersTv;
    @Bind(R.id.clear_seachset_ib)
    ImageButton clearSeachsetIb;
    @Bind(R.id.type_search_tv)
    TextView typeSearchTv;
    @Bind(R.id.search_ll)
    LinearLayout searchLl;
    @Bind(R.id.type_search_ll)
    LinearLayout typeSearchLl;
    @Bind(R.id.special_search_ll)
    LinearLayout specialSearchLl;

    private View head_status_view;
    private GridLayoutManager gridLayoutManager;
    private List<YouLikeGoodsBean> goodsLists;
    private RecycleViewGridAdapter recycleViewAdapter;

    private int search_type = -1;
    private int sale_order = 2;
    private int hot_order = 2;
    private int price_order = 1;

    private boolean has_more = false;
    private int total_page = 1;
    private int current_page = 1;
    private final static int ONEPAGENUM = 10;
    private String searchKey;
    private String searchValue;
    private String searchAddation = "";
    private String searchStoreId = "";
    private String searchStoreName = "";

    private boolean noKey = false;

    private final static String HEAD_URL = "http://www.xilingou.com/mobile/index.php?act=goods&op=goods_list";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.goods_searchresult_layout);
        ButterKnife.bind(this);

        head_status_view = findViewById(R.id.searchresult_menubar_inc);
        super.MenuWidget(head_status_view);

        initViews();
        specialSearchLl.setVisibility(View.GONE);
        typeSearchLl.setVisibility(View.GONE);
        searchLl.setVisibility(View.VISIBLE);
        searchKey = getIntent().getStringExtra("SearchKeyType");
        searchValue = getIntent().getStringExtra("SearchKeyWord");
        if (searchKey.equals("keyword")) {
            switch (searchValue) {
                case "今日上新":
                    searchValue = "";
                    typeClick(0);
                    break;
                case "热门推荐":
                    searchValue = "";
                    typeClick(2);
                    break;
                case "店铺搜索":
                    specialSearchLl.setVisibility(View.VISIBLE);
                    searchStoreId = getIntent().getStringExtra("SearchStoreId");
                    searchStoreName = getIntent().getStringExtra("SearchStoreName");
                    specialSearchTv.setText(searchStoreName);
                    searchValue = "";
                    searchresultSearchEt.setHint("寻找本店铺内宝贝");
                    typeClick(0);
                    break;
                default:
                    searchresultSearchEt.setText(searchValue);
                    typeClick(0);
                    break;
            }
        } else {
            typeSearchLl.setVisibility(View.VISIBLE);
            searchLl.setVisibility(View.GONE);
            searchAddation = getIntent().getStringExtra("SearchKeyAddion");
            typeSearchTv.setText(searchAddation);
            getSearchResult();
        }
    }

    private void initViews() {
        searchresultGobackIb.setOnClickListener(this);
        searchresultSearchIb.setOnClickListener(this);
        clearSeachsetIb.setOnClickListener(this);

        searchOrderDefaultTv.setOnClickListener(this);
        searchOrderSalesTv.setOnClickListener(this);
        searchOrderNewestTv.setOnClickListener(this);
        searchOrderPriceLl.setOnClickListener(this);
        searchresultBuycarIb.setOnClickListener(this);

        gridLayoutManager = new GridLayoutManager(this, 2);
        goodsLists = new ArrayList<>();
        recycleViewAdapter = new RecycleViewGridAdapter(goodsLists);

        searchgoodsRecycleView.setLayoutManager(gridLayoutManager);
        searchgoodsRecycleView.setAdapter(recycleViewAdapter);

        recycleViewAdapter.setOnItemClickListener(new OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View view, int data) {
                //TODO
                Intent detailIntent = new Intent(SearchResultActivity.this, GoodsDetailActivity.class);
                detailIntent.putExtra("GoodId", goodsLists.get(data).getGoodId());
                startActivity(detailIntent);
            }
        });

        searchgoodsRecycleView.setLoadMoreListener(new LoadMoreRecyclerView.LoadMoreListener() {
            @Override
            public void onLoadMore() {
                searchgoodsRecycleView.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        getSearchResult();
                    }
                }, 1000);
            }
        });

        searchgoodsRecycleSwiperefreshlayout.setColorSchemeColors(R.color.domain_orange, R.color.green,
                R.color.blue, R.color.yellow);


        searchgoodsRecycleSwiperefreshlayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                Log.d("zhangxiaoxidebug", "invoke onRefresh...");
                goodsLists.clear();
                has_more = false;
                current_page = 1;
                total_page = 1;
                getSearchResult();
            }
        });

        searchresultSearchEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.toString().isEmpty()) {
                    clearSeachsetIb.setVisibility(View.GONE);
                } else {
                    clearSeachsetIb.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    private void clearText() {
        searchOrderDefaultTv.setTextColor(getResources().getColor(R.color.grey_text_todaynew));
        searchOrderNewestTv.setTextColor(getResources().getColor(R.color.grey_text_todaynew));
        searchOrderSalesTv.setTextColor(getResources().getColor(R.color.grey_text_todaynew));
        searchOrderPriceTv.setTextColor(getResources().getColor(R.color.grey_text_todaynew));
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.searchresult_goback_ib:
                finish();
                break;
            case R.id.searchresult_search_ib:
                searchValue = searchresultSearchEt.getText().toString();
                if (!searchValue.isEmpty()) {
                    MainActivity.myDBHelper.insertList(searchValue);
                }
                clearParams();
                searchKey = "keyword";
                getSearchResult();
                break;
            case R.id.search_order_default_tv:
                typeClick(0);
                break;
            case R.id.search_order_sales_tv:
                typeClick(1);
                break;
            case R.id.search_order_newest_tv:
                typeClick(2);
                break;
            case R.id.search_order_price_ll:
                typeClick(3);
                break;
            case R.id.searchresult_buycar_ib:
                if (MainActivity.myLogin.isLoginState()) {
                    Intent buycarInt = new Intent(this, BuyCarActivity.class);
                    startActivityForResult(buycarInt, 1);
                } else {
                    Toast.makeText(getApplication(), "您还没有登录！", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.clear_seachset_ib:
                searchresultSearchEt.setText("");
                break;
            default:
                break;
        }
    }

    private void typeClick(int type) {
        switch (type) {
            case 0:
                if (search_type != 0) {
                    clearText();
                    searchOrderDefaultTv.setTextColor(getResources().getColor(R.color.domain_orange));
                    clearParams();
                    search_type = 0;
                    getSearchResult();
                }
                break;
            case 1:
                if (search_type != 1) {
                    clearText();
                    searchOrderSalesTv.setTextColor(getResources().getColor(R.color.domain_orange));
                    clearParams();
                    search_type = 1;
                    getSearchResult();
                }
                break;
            case 2:
                if (search_type != 2) {
                    clearText();
                    searchOrderNewestTv.setTextColor(getResources().getColor(R.color.domain_orange));
                    clearParams();
                    search_type = 2;
                    getSearchResult();
                }
                break;
            case 3:
                if (search_type != 3) {
                    searchOrderPriceIv.setImageResource(R.drawable.di);
                    price_order = 1;
                } else {
                    if (price_order == 1) {
                        searchOrderPriceIv.setImageResource(R.drawable.gao);
                        price_order = 2;
                    } else {
                        searchOrderPriceIv.setImageResource(R.drawable.di);
                        price_order = 1;
                    }
                }
                clearText();
                searchOrderPriceTv.setTextColor(getResources().getColor(R.color.domain_orange));
                clearParams();
                search_type = 3;
                getSearchResult();
                break;
            default:
                break;
        }
    }

    private void clearParams() {
        goodsLists.clear();
        current_page = 1;
        total_page = 1;
        has_more = false;
    }

    private void getSearchResult() {
        String order = "2";
        if (search_type < 3) {
            order = "2";
        } else {
            order = String.valueOf(price_order);
        }

        String theUrl = HEAD_URL + "&key=" + search_type + "&page=" + ONEPAGENUM + "&curpage=" + current_page +
                "&order=" + order + "&" + searchKey + "=" + searchValue + "&store_id=" + searchStoreId;

        Log.i("zhangxiaoxidebug", "theUrl=" + theUrl);
        HttpUtils http = new HttpUtils();
        http.configCurrentHttpCacheExpiry(200);
        //http.send(HttpRequest.HttpMethod.POST, HEAD_URL, params,new RequestCallBack<String>() {

        http.send(HttpRequest.HttpMethod.GET, theUrl, new RequestCallBack<String>() {
                    @Override
                    public void onLoading(long total, long current, boolean isUploading) {
                    }

                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        searchgoodsRecycleSwiperefreshlayout.setRefreshing(false);
                        int result = parseProject(responseInfo.result);
                        switch (result) {
                            case 1:
                                break;
                            case 0:
                                Toast.makeText(getApplicationContext(), "商品列表查询失败！", Toast.LENGTH_LONG).show();
                                break;
                            default:
                                break;
                        }
                    }


                    @Override
                    public void onStart() {
                        searchgoodsRecycleSwiperefreshlayout.setRefreshing(true);
                    }

                    private int parseProject(String result) {
                        Log.i("zhangxiaoxidebug", "search_result=" + result);
                        try {
                            JSONObject jsObjectCode = new JSONObject(result);
                            int code = jsObjectCode.getInt("code");
                            if (code != 200) {
                                return 0;
                            }

                            has_more = jsObjectCode.getBoolean("hasmore");
                            total_page = jsObjectCode.getInt("page_total");
                            if (has_more) {
                                if (current_page < total_page) {
                                    current_page++;
                                }
                            }

                            JSONObject jsObjectDatas = jsObjectCode.getJSONObject("datas");
                            JSONArray jsArrayGoodsItems = jsObjectDatas.getJSONArray("goods_list");

                            if (jsArrayGoodsItems.length() > 0) {
                                searchgoodsRecycleView.setVisibility(View.VISIBLE);
                                myordersNoordersTv.setVisibility(View.GONE);

                                for (int good = 0; good < jsArrayGoodsItems.length(); good++) {
                                    JSONObject jsObjectTheGood = jsArrayGoodsItems.getJSONObject(good);
                                    String goodId = jsObjectTheGood.getString("goods_id");
                                    String goods_name = jsObjectTheGood.getString("goods_name");
                                    String goods_price = jsObjectTheGood.getString("goods_price");
                                    String goods_image = jsObjectTheGood.getString("goods_image_url");
                                    String goods_salenum = jsObjectTheGood.getString("goods_salenum");
                                    goodsLists.add(new YouLikeGoodsBean(goodId, goods_image, goods_name, goods_price, goods_salenum));
                                }
                                searchgoodsRecycleView.setAutoLoadMoreEnable(has_more);
                                recycleViewAdapter.notifyDataSetChanged();
                                searchgoodsRecycleView.setLoadingMore(false);
                            } else {
                                searchgoodsRecycleView.setVisibility(View.GONE);
                                myordersNoordersTv.setVisibility(View.VISIBLE);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                            return 0;
                        }
                        return 1;
                    }

                    @Override
                    public void onFailure(HttpException error, String msg) {
                        Log.i("zhangxiaoxidebug", "getIndex....onFailure msg=" + msg);
                        searchgoodsRecycleSwiperefreshlayout.setRefreshing(false);
                        Toast.makeText(getApplicationContext(), "读取数据失败，请检查网络设置！", Toast.LENGTH_LONG).show();
                    }
                }
        );
    }

    private void getStoreGoods() {
        String order = "2";
        if (search_type < 3) {
            order = "2";
        } else {
            order = String.valueOf(price_order);
        }

        String theUrl = HEAD_URL + "&key=" + search_type + "&page=" + ONEPAGENUM + "&curpage=" + current_page +
                "&order=" + order + "&" + searchKey + "=" + searchValue;

        Log.i("zhangxiaoxidebug", "theUrl=" + theUrl);
        HttpUtils http = new HttpUtils();
        http.configCurrentHttpCacheExpiry(200);
        //http.send(HttpRequest.HttpMethod.POST, HEAD_URL, params,new RequestCallBack<String>() {

        http.send(HttpRequest.HttpMethod.GET, theUrl, new RequestCallBack<String>() {
                    @Override
                    public void onLoading(long total, long current, boolean isUploading) {
                    }

                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        searchgoodsRecycleSwiperefreshlayout.setRefreshing(false);
                        int result = parseProject(responseInfo.result);
                        switch (result) {
                            case 1:
                                break;
                            case 0:
                                Toast.makeText(getApplicationContext(), "商品列表查询失败！", Toast.LENGTH_LONG).show();
                                break;
                            default:
                                break;
                        }
                    }


                    @Override
                    public void onStart() {

                    }

                    private int parseProject(String result) {
                        Log.i("zhangxiaoxidebug", "search_result=" + result);
                        try {
                            JSONObject jsObjectCode = new JSONObject(result);
                            int code = jsObjectCode.getInt("code");
                            if (code != 200) {
                                return 0;
                            }

                            has_more = jsObjectCode.getBoolean("hasmore");
                            total_page = jsObjectCode.getInt("page_total");
                            if (has_more) {
                                if (current_page < total_page) {
                                    current_page++;
                                }
                            }

                            JSONObject jsObjectDatas = jsObjectCode.getJSONObject("datas");

                            //goods 内容为底部的商品列表
                            {
                                JSONArray jsArrayGoodsItems = jsObjectDatas.getJSONArray("goods_list");
                                for (int good = 0; good < jsArrayGoodsItems.length(); good++) {
                                    JSONObject jsObjectTheGood = jsArrayGoodsItems.getJSONObject(good);
                                    String goodId = jsObjectTheGood.getString("goods_id");
                                    String goods_name = jsObjectTheGood.getString("goods_name");
                                    String goods_price = jsObjectTheGood.getString("goods_price");
                                    String goods_image = jsObjectTheGood.getString("goods_image_url");
                                    String goods_salenum = jsObjectTheGood.getString("goods_salenum");
                                    goodsLists.add(new YouLikeGoodsBean(goodId, goods_image, goods_name, goods_price, goods_salenum));
                                }
                                searchgoodsRecycleView.setAutoLoadMoreEnable(has_more);
                                recycleViewAdapter.notifyDataSetChanged();
                                searchgoodsRecycleView.setLoadingMore(false);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                            return 0;
                        }
                        return 1;
                    }

                    @Override
                    public void onFailure(HttpException error, String msg) {
                        Log.i("zhangxiaoxidebug", "getIndex....onFailure msg=" + msg);
                        searchgoodsRecycleSwiperefreshlayout.setRefreshing(false);
                        Toast.makeText(getApplicationContext(), "读取数据失败，请检查网络设置！", Toast.LENGTH_LONG).show();
                    }
                }
        );
    }
}
